const wsUrl = "ws://127.0.0.1:8888/";
let status = false;
let socket = getSocket();
const Actions = new Map();
const StatusListener = new Map();
function getSocket() {
  if (!status) {
    const socket = new WebSocket(wsUrl);
    socket.onclose = () => {
      ChangeStatus(false);
      getSocket();
    };
    socket.onopen = () => {
      ChangeStatus(true);
      socket.send("init");
    };
    socket.onmessage = (e) => {
      Actions.forEach((Action) => {
        Action(e.data);
      });
    };
    return socket;
  }
}
function ChangeStatus(value) {
  status = value;
  StatusListener.forEach((Listener) => {
    Listener(value);
  });
}
function SetAction(key, Action) {
  if (Actions.has(key) && typeof Action != "function") return false;
  Actions.set(key, Action);
  return true;
}
function DeleteAction(key) {
  return Actions.delete(key);
}
function SetStatusListener(key, Listener) {
  if (StatusListener.has(key) && typeof Listener != "function") return false;
  StatusListener.set(key, Listener);
  return true;
}
function DeleteStatusListener(key) {
  return StatusListener.delete(key);
}
function Send(msg) {
  if (status && typeof msg == "string") {
    socket.send(msg);
    return true;
  }
  return false;
}

const ws = {};
ws.SetStatusListener = SetStatusListener;
ws.DeleteStatusListener = DeleteStatusListener;
ws.SetAction = SetAction;
ws.DeleteAction = DeleteAction;
ws.Send = Send;
export default ws;

